package com.wx.session;

import java.util.ArrayList;
import java.util.List;

public class SessionList {
	private static List<Session> sessionList = new ArrayList<Session>();

	public static List<Session> getSessionList() {
		return sessionList;
	}

	public static void setSessionList(List<Session> sessionList) {
		SessionList.sessionList = sessionList;
	}

	public SessionList() {
	}

	// 查找session中是否有指定项
	public static int search(String openid) {
		if (sessionList.isEmpty())
			return -1;
		else {
			int size = sessionList.size();
			for (int i = 0; i < size; i++) {
				if (sessionList.get(i).getOpenid().equals(openid))
					return i;
			}
		}
		return -1;
	}

	// 计时器递减
	public static void timeMin(String openid) {
		int i = search(openid);
		if (i >= 0)
			sessionList.get(i).timeMin();
	}

	// 判断计时器是否为零
	public static boolean timeStop(String openid) {
		int i = search(openid);
		if (sessionList.get(i).timeStop())
			return true;
		else
			return false;
	}

	// 移除session
	public static void remove(String openid) {
		int i = search(openid);
		if (i >= 0)
			sessionList.remove(i);
	}

	// 向session中存入数据
	public static void setSeesion(String name, String value, String openid) {
		System.out.println("setSeesion " + name + " " + value + " " + openid);
		int i = search(openid);
		if (i >= 0) {
			SessionData data = new SessionData();
			data.setName(name);
			data.setValue(value);
			sessionList.get(i).set(data);
		}
	}

	// 创建session
	public static void setSeesion(String openid) {
		System.out.println("setSeesion " + openid);
		int i = search(openid);
		if (i < 0) {
			// 建立线程
			System.out.println("创建计时线程");
			Runnable t = new SessionThread(openid);
			Thread time = new Thread(t);
			time.start();
			Session session = new Session();
			session.setOpenid(openid);
			sessionList.add(session);
		}
	}

	public static void removeData(String name, String openid) {
		int i = search(openid);
		if (i >= 0) {
			sessionList.get(i).remove(name);
		}
	}

	public static String getData(String name, String openid) {
		System.out.println("getData " + name + " " + openid);
		int i = search(openid);
		if (i >= 0) {
			String value = sessionList.get(i).get(name);
			System.out.println(name + "值为 " + value);
			return value;
		}
		return null;
	}

	public static boolean sleep() {
		return true;
	}

	public static long getTime(String openid) {
		int i = search(openid);
		if (i >= 0) {
			return sessionList.get(i).whatTime();
		}
		return 0;
	}
}
